/*
 * @Author: wangke
 * @Date: 2025-04-15 00:03:08
 * @LastEditors: wangke
 * @LastEditTime: 2025-08-01 00:47:53
 * 
 */
#include "App_98357.h"
#include "i2s.h"
#include <FS.h>
#include <SD.h>
#include "App_Hello.h"
#include "App_I2S.h"
#include "Common.h"
#include "Wav.h"
const int offset = 0x2C;
char data[800];

void App_AudioInit()
{
    I2S_Init();
    //I2S_RecoderInit();
    // if (!I2S.begin(I2S_PHILIPS_MODE, 20000, 16)) {
    //     printfme("Failed to initialize I2S!\r\n");
    //     while (1); // do nothing
    // }
}

const int record_time = 10;  // second
const char filename[] = "/sound.wav";

const int headerSize = 44;
const int waveDataSize = record_time * 88000;
const int numCommunicationData = 8000;
const int numPartWavData = numCommunicationData/4;
byte header[headerSize];
char communicationData[numCommunicationData];
char partWavData[numPartWavData];
File file;


void App_Recorder()
{
  CreateWavHeader(header, waveDataSize);
  SD.remove(filename);
  file = SD.open(filename, FILE_WRITE);
  if (!file) return;
  file.write(header, headerSize);
  I2S_RecoderInit();
  printfme("start record\r\n");
  for (int j = 0; j < waveDataSize/numPartWavData; ++j) {
    I2S_Read(communicationData, numCommunicationData);
    for (int i = 0; i < numCommunicationData/8; ++i) {
      partWavData[2*i] = communicationData[8*i + 2];
      partWavData[2*i + 1] = communicationData[8*i + 3];
    }
    file.write((const byte*)partWavData, numPartWavData);
  }
  file.close();
  printfme("finish\r\n");
}

void App_PlayAudio()
{   
    //SD.begin();
    File file = SD.open("/MUSIC/daoxiang.wav");  // 44100Hz, 16bit, stereo, linear PCM
    file.seek(offset);
    I2S_Init();
    while (file.readBytes(data, sizeof(data))) {
      I2S_Write(data, sizeof(data));
    }
    file.close();
    I2S_Init();
}